package com.ruoyi.listener.improve;

import com.ruoyi.quality.domain.bo.QualityContinuousImprovementBo;
import com.ruoyi.quality.domain.vo.QualityContinuousImprovementVo;
import com.ruoyi.quality.service.IQualityContinuousImprovementService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngines;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;

@Component
public class RateListener implements TaskListener {
    @Resource
    public IQualityContinuousImprovementService improvementService;

    private static RateListener rateListener;

    @PostConstruct
    public void init() {
        rateListener = this;
        rateListener.improvementService = this.improvementService;
    }

    @Override
    public void notify(DelegateTask delegateTask) {

        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();

        Map<String, Object> variables = taskService.getVariables(delegateTask.getId());
        String procId = delegateTask.getProcessInstanceId();
        QualityContinuousImprovementVo vo = rateListener.improvementService.queryByProcessInstanceId(procId);
        QualityContinuousImprovementBo bo = new QualityContinuousImprovementBo();
        BeanUtils.copyProperties(vo,bo);

        Integer totalScore = bo.getTotalScore();
        Integer score = Integer.parseInt(String.valueOf(variables.get("score")));
        if (totalScore!=null){
            bo.setTotalScore(totalScore+score);
        }else {
            bo.setTotalScore(score);
        }

        Integer review = bo.getReview();
        if (review == null){
            review = 0;
        }
        review++;
        bo.setReview(review);

        rateListener.improvementService.updateByBo(bo);
    }
}
